package com.youxin.foundation.db.utils;



import java.util.Random;

import com.youxin.foundation.db.common.TwitterSnowflake;

/**
 * 数据库表主键生成方法
 * @author yingde.cao
 *
 */
public class KeyGenerationUtils {
	private static final int DEFAULT_SERVER_ID=-1;
	private static int server_id=DEFAULT_SERVER_ID;
	private static TwitterSnowflake snowflake=null;
	static {
		if(server_id==DEFAULT_SERVER_ID)
		{
			synchronized (KeyGenerationUtils.class) {
				if(server_id==DEFAULT_SERVER_ID){
					try {
						String serverIdStr=System.getProperty("server.id");
						server_id=new Integer(serverIdStr);
					}catch (Exception e) {
						server_id=new Random().nextInt(1024);
					}
					finally {
					}
				}
			}
		}		
	}
	
	private static TwitterSnowflake getTwitterSnowFlake() {
		if (snowflake==null) {
			synchronized (KeyGenerationUtils.class) {
				if(snowflake==null){
					snowflake=new TwitterSnowflake(server_id);
				}
			}
		}
		return snowflake;
	}
	
	/**
	 * 通用表id生成方法
	 * @return long
	 */
	public static long generateKey() {		
		long id=getTwitterSnowFlake().next();
		return id;
	}
	
	
}
